package com.gxm.base.datatype.collection.set;

import java.util.HashSet;
import java.util.Iterator;

/*
 * 往hashSet集合中存储Person对象。如果姓名和年龄相同，视为同一个人。视为相同元素。
 */
public class HashSetTest {

    /**
     * @param args
     */
    public static void main(String[] args) {


        HashSet hs = new HashSet();

        /*
         * HashSet集合数据结构是哈希表，所以存储元素的时候，
         * 使用的元素的hashCode方法来确定位置，如果位置相同，在通过元素的equals来确定是否相同。
         *
         */

        hs.add(new Person("lisi4",24));
        hs.add(new Person("lisi7",27));
        hs.add(new Person("lisi1",21));
        hs.add(new Person("lisi9",29));
        hs.add(new Person("lisi7",27));


        Iterator it = hs.iterator();

        while(it.hasNext()){
            Person p = (Person)it.next();
            System.out.println(p);
//			System.out.println(p.getName()+"...."+p.getAge());
        }
    }

}


class Person implements Comparable{

    private String name;
    private int age;


    public Person() {
        super();

    }
    public Person(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }



    @Override
    public int hashCode() {
//		System.out.println(this+".......hashCode");

        return name.hashCode()+age*27;
//		return 100;
    }
    @Override
    public boolean equals(Object obj) {

        if(this == obj)
            return true;
        if(!(obj instanceof Person))
            throw new ClassCastException("类型错误");

//		System.out.println(this+"....equals....."+obj);
        Person p = (Person)obj;



        return this.name.equals(p.name) && this.age == p.age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String toString(){
        return name+":"+age;
    }
    @Override
    public int compareTo(Object o) {

        Person p = (Person)o;

        int  temp = this.age-p.age;
        return temp==0?this.name.compareTo(p.name):temp;

//		int  temp = this.name.compareTo(p.name);
//		return temp==0?this.age-p.age:temp;

		/*
		if(this.age>p.age)
			return 1;
		if(this.age<p.age)
			return -1;

		else{

			return this.name.compareTo(p.name);
		}
		*/

    }
}